package cn.itsource.ymcc.consumer;

import cn.itsource.ymcc.constant.Constants;
import cn.itsource.ymcc.constant.VideoConstants;
import cn.itsource.ymcc.domain.MediaFile;
import cn.itsource.ymcc.result.JsonResult;
import cn.itsource.ymcc.service.IMediaFileService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

@Slf4j
@Component
@RocketMQMessageListener(
        consumerGroup = "MediaConsumer",
        topic = VideoConstants.TOPIC_COURSE_VIDEO_PUSH_TO_SRS,
        selectorExpression = VideoConstants.TAGS_COURSE_VIDEO_PUSH_TO_SRS
)
public class MediaConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private IMediaFileService mediaFileService;

    @Override
    public void onMessage(MessageExt message) {
        try {
            log.info("媒体中心消费者收到消息.......开始处理消息.......");
            byte[] body = message.getBody();
            String jsonStr = new String(body, Constants.UTF8);
            log.info("消息内容：{}", jsonStr);
            //json字符串转实体类
            MediaFile mediaFile = JSON.parseObject(jsonStr, MediaFile.class);
            //开始推流
            JsonResult jsonResult = mediaFileService.handleFile2m3u8(mediaFile);
            log.info("异步推流结果：{}", jsonResult.getSuccess()? "成功":"失败");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}